package dev.langchain4j.example.agent;

import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.Result;
import dev.langchain4j.service.TokenStream;
import dev.langchain4j.service.tool.ToolExecution;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;


@RequestMapping("/sport")
@RestController
public class CustomerSupportAgentController {

    private final CustomerSupportAgent customerSupportAgent;

    public CustomerSupportAgentController(CustomerSupportAgent customerSupportAgent) {
        this.customerSupportAgent = customerSupportAgent;
    }

    @GetMapping("/customerSupportAgent")
    public String customerSupportAgent(@RequestParam String sessionId, @RequestParam String userMessage) {
        Result<String> result = customerSupportAgent.answer(sessionId, userMessage);
        System.out.println(result.content());

        return result.content();
    }


    @RequestMapping(value = "/chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> stream(@RequestParam String message, @RequestParam String sessionId) {

        TokenStream stream = customerSupportAgent.stream(sessionId, message, LocalDate.now().toString());

        return Flux.create(sink -> {

            stream.onPartialResponse(s -> {
                        sink.next(s);
                    })
                    .onToolExecuted((ToolExecution toolExecution) -> {

                        sink.next("正在执行工具: " + toolExecution.request().name() + "\n");
                        sink.next("工具参数: " + toolExecution.request().arguments() + "\n");
                        sink.next("工具执行结果: " + toolExecution.result() + "\n");

                    })

                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });

    }


}
